#pragma once
#include <iostream>
#include <string>
#include "Log.hpp"
#include <sys/socket.h>
#include <netinet/in.h>
#include <strings.h>
#include <arpa/inet.h>

#define COV(addr) (struct sockaddr *)(&addr)

using namespace LogModule;

class InetAddr
{
public:
    InetAddr(){}
    
    InetAddr(struct sockaddr_in &addr)
        : _addr(addr), _socklen(sizeof(addr))
    {
        SetAddr(addr);
    }

    InetAddr(std::string ip, uint16_t port)
        : _ip(ip), _port(port), _socklen(0)
    {
        bzero(&_addr, sizeof(_addr));
        _addr.sin_family = AF_INET;
        _addr.sin_port = htons(_port);
        inet_aton(_ip.c_str(), &_addr.sin_addr);
        _socklen = sizeof(_addr);
    }

    InetAddr(uint16_t port)
        : _port(port), _ip("0.0.0.0"), _socklen(0)
    {
        bzero(&_addr, sizeof(_addr));
        _addr.sin_family = AF_INET;
        _addr.sin_port = htons(_port);
        _addr.sin_addr.s_addr = INADDR_ANY;
        _socklen = sizeof(_addr);
    }
    void SetAddr(struct sockaddr_in client)
    {
        _addr = client;
        _ip = inet_ntoa(_addr.sin_addr);
        _port = ntohs(_addr.sin_port);
    }

    std::string NetAddrStr()
    {
        return _ip;
    }

    struct sockaddr *NetAddrPtr()
    {
        return COV(_addr);
    }

    const socklen_t &GetLen()
    {
        return _socklen;
    }

    std::string GetIP()
    {
        return _ip;
    }

    uint16_t GetPort()
    {
        return _port;
    }

private:
    struct sockaddr_in _addr;
    std::string _ip;
    uint16_t _port;
    socklen_t _socklen;
};